package com.jxc.jxcmanage.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import com.jxc.jxcmanage.code.entity.UserInfo;
import com.jxc.jxcmanage.constants.Constant;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * session 监听 用于缓存account状态
 * 2018-11-14 15:12
 */

@WebListener
@Configuration
public class SessionListener implements HttpSessionListener, HttpSessionAttributeListener {
	private static final Logger LOGGER = LoggerFactory.getLogger(SessionListener.class);
	private static final Map<Integer, String> ACCOUNT_STATUS_MAP = new ConcurrentHashMap<>();

	@Override
	public void sessionCreated(HttpSessionEvent se) {

	}

	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		UserInfo userInfo = (UserInfo) se.getSession().getAttribute(Constant.ACCOUNT_SESSION_KEY);
		if (userInfo != null && ACCOUNT_STATUS_MAP.containsKey(userInfo.getId())) {
			ACCOUNT_STATUS_MAP.remove(userInfo.getId());
		}
		LOGGER.info("User session has been destroyed.");
	}

	@Override
	public void attributeAdded(HttpSessionBindingEvent se) {
		LOGGER.info("User info has been saved in session.");
		UserInfo userInfo = (UserInfo) se.getValue();
		ACCOUNT_STATUS_MAP.put(userInfo.getId(), userInfo.getUserCode());
	}

	@Override
	public void attributeRemoved(HttpSessionBindingEvent se) {

	}

	@Override
	public void attributeReplaced(HttpSessionBindingEvent se) {
		LOGGER.info("User info has been replaced in session.");
		UserInfo userInfo = (UserInfo) se.getValue();
		ACCOUNT_STATUS_MAP.put(userInfo.getId(), userInfo.getUserCode());
	}

	public static void updateAccountStatus(Integer accountId, String status) {
		ACCOUNT_STATUS_MAP.put(accountId, status);
	}

	public static Map<Integer, String> getAccountStatusMap() {
		return ACCOUNT_STATUS_MAP;
	}
}
